package com.luoqiu.cinema.controller;

import com.luoqiu.cinema.common.Result;
import com.luoqiu.cinema.entity.UserInfo;
import com.luoqiu.cinema.service.UserInfoService;
import com.luoqiu.cinema.util.UserInfoUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
public class UserInfoController {

    @Resource
    private UserInfoService userInfoService;
    @Resource
    private UserInfoUtil userInfoUtil;

    @GetMapping("/login")
    public Result login(UserInfo user) {

        //用户认证信息
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        try {
            //进行验证，这里可以捕获异常，然后返回对应信息
            subject.login(usernamePasswordToken);
        } catch (UnknownAccountException e) {
            return Result.fail("用户不存在");
        } catch (AuthenticationException e) {
            return Result.fail("账号密码错误");
        } catch (AuthorizationException e) {
            return Result.fail("权限不足");
        }
        return Result.success(userInfoUtil.getInfo());
    }


    /**
     * 用户的注册或者修改
     * @param userInfo
     * @return
     */
    @RequestMapping(value = "/u/regis")
    public Result<String> regis(@RequestBody UserInfo userInfo) {
        userInfoService.regis(userInfo);
        return Result.success("OK");
    }


    /**
     * 签到
     * @return
     */
    @GetMapping(value = "/u/sign")
    public Result<String> sign(){
        userInfoService.sign();
        return Result.success(null);
    }

    /**
     * 抽奖
     * @return
     */
    @GetMapping(value = "/u/luck")
    public Result<String> luck() {
        userInfoService.luck();
        return Result.success(null);
    }
}
